package net.nettytlv.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import net.nettytlv.domain.Packet;

/**
 * bytes to object.
 */
@Sharable
public class ObjectDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        try {
            Packet packet = Packet.builder()
                    .type(byteBuf.readByte())
                    .length(byteBuf.readShort())
                    .build();
            final byte[] content = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(content);
            packet.setValue(content);

            ctx.fireChannelRead(packet);
        } finally {
            ReferenceCountUtil.release(byteBuf);
        }
    }
}
